package cn.gcjxsc.messaging.sink;

import cn.gcjxsc.common.consts.PayStatus;
import cn.gcjxsc.common.data.notify.order.ResultHandleData;
import cn.gcjxsc.common.util.ValidatorUtil;
import cn.gcjxsc.consts.merchant.MerchantAccountType;
import cn.gcjxsc.data.recharge.RechargeData;
import cn.gcjxsc.entity.mall.BaseOrder;
import cn.gcjxsc.entity.merchant.Merchant;
import cn.gcjxsc.service.mall.OrderService;
import cn.gcjxsc.service.merchant.MerchantService;
import cn.gcjxsc.service.merchant.RechargeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.SubscribableChannel;

import java.math.BigDecimal;


/**
 * @author pumbaa
 * @since 1.0
 */
@EnableBinding(RechargeResultSink.Sink.class)
public class RechargeResultSink {

    private Logger logger = LoggerFactory.getLogger(RechargeResultSink.class);
    @Autowired
    private RechargeService rechargeService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private MerchantService merchantService;

    @StreamListener(Sink.QUEUE_NAME)
    public void process(ResultHandleData data) {
        logger.info("接收回调通知.{}", System.currentTimeMillis()/1000);
        String msg = ValidatorUtil.validate(data);
        if (null != msg) {
            logger.error("数据检验不通过.{}", msg);
            return;
        }
        String sn = data.getSn();
        BaseOrder order = orderService.findRechargeOrderBySn(sn);
        if (null== order) {
            logger.error("订单不存在.{}", sn);
            return;
        }
        if (order.getPayStatus() == PayStatus.PAID) {
            logger.info("该订单已被处理,重复请求.{}", sn);
            return;
        }
        Merchant merchant = merchantService.findById(order.getOwnerId());
        if (null == merchant) {
            logger.error("商户信息不存在.{}", sn);
            return;
        }
        RechargeData rechargeData = new RechargeData();
        rechargeData.setAmount(BigDecimal.valueOf(data.getAmount()).multiply(BigDecimal.valueOf(0.01)));
        rechargeData.setChannel(data.getChannel());
        rechargeData.setTradeNo(data.getTradeNo());
        rechargeData.setOutTradeNo(data.getOutTradeNo());
        rechargeData.setRemark("商户充值");
        logger.info("金额:{}, {}", rechargeData.getAmount(), data.getAmount());
        try {
            rechargeService.doRecharge(merchant, MerchantAccountType.WX_CASH, rechargeData, order);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("充值处理失败.{}, {}", sn, e.getMessage());
        }
    }

    public interface Sink {
        String QUEUE_NAME = "machine_payment_recharge_order_input";

        @Input(QUEUE_NAME)
        SubscribableChannel input();
    }
}
